﻿
//获取流程、表单、页面Json数据
//jtype类型 0流程 1表单和页面 2表单 3页面
function GetFlowFormJson(jtype) {
    var cdata = null;
    var sendObj = {};
    sendObj.type = jtype
    $.ajax({
        url: "../WorkflowEngine.asmx/GetFlowFormJsonStr",
        type: "POST",
        async: false,
        cache: false,
        data: JSON.stringify(sendObj),
        contentType: "application/json",
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("取得数据时发生远程请求错误！");
        },
        success: function(result) {
            result = commFun.GetResultStr(result);
            try {
                cdata = JSON.parse(result);
            } catch (e) { alert("获取Json数据出错：" + e); }
        }
    });
    return cdata;
}

//初始化下拉框或弹出框并设定值
//id下拉框Id
//isuserval为true时取value的值，否则取页面初始化时此下拉框的值
//value用户定义的值
//cdata 是用于绑定下拉框的Json数据，不为null时，使用此值绑定下拉框
//keyword是查询占位符，用于替换下拉框查数据项的查询数据集中的关键字
//reqplus补充request参数，可以"[req1][val1]|[req2][val2]"的形式补充，以便替换数据集中的{Request【参数名】}
//setid 数据集id 表单请传入。页面不传入时，默认取自身条目项数据集
function UserLoadElementData(id, isuserval, value, cdata, keyword, reqplus, setid) {
    //var cdata = [{ text: '显示1', id: '20' }, { text: '显示2', id: '30' }, { text: '显示3', id: '31'}];
    var obj = document.getElementById(id);
    if (!obj) return;
    var dyCat = $(obj).attr("dytype");
    var bForm = id.indexOf("_||") >= 0;
    if (bForm) {
        dyCat = "12";
        //id = id.substring(0, id.length - 1);
    }
    if (!cdata) {
        var sendObj = {};
        sendObj.iid = $("#hIidPlus").val() + "|" + reqplus;
        sendObj.fid = $("#hfid").val(); 
        sendObj.action = dyCat;
        sendObj.objid = id.substring(3); 
        sendObj.input_index = $("#hinput_index").val();
        sendObj.keyword = keyword;
        sendObj.table = (setid || bForm) ? setid : jQuery.data(obj, "itemset");
        $.ajax({
            url: (bForm ? '../DynamicForm/GetData.aspx' : 'GetData.aspx'),
            type: 'Post',
            async: false,
            cache: false,
            data: sendObj,
            dataType: 'text',
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                alert("取得数据时发生远程请求错误！");
            },
            success: function(result) {
                result = commFun.GetResultStr(result);
                if (result.indexOf(backErrMsg) > 0) {
                    alert("请求错误！请联系管理员查看日志。");
                    result = 0;
                }else
                    cdata = JSON.parse(result);
            }
        }); 
    }
    if (cdata) {
        switch (dyCat) {
            case "12":
                if(!bForm)
                    InitComboBox(id, cdata, isuserval, value);
                else
                    InitComboBoxForm(id, cdata, isuserval, value);
                break;
            case "17":
                InitTree(id, cdata, isuserval, value);
                break;
            case "37":
                InitCmbList(id, cdata, isuserval, value);
                break;
            case "38":
                InitCmbTree(id, cdata, isuserval, value);
                break;
        }
    }
}
//if (dyObj.attr("inited") == "0")
//formCtrlValOp(id, 1, "", "", userval);
function setHideVal(did, newValue) {
    document.getElementById(did + "H").value = newValue;
    $(document.getElementById(did + "H")).trigger('change');
}

function InitComboBoxForm(did, cdata, isuserval, value) {
    var obj = document.getElementById(did);
    if (cdata == null) {
        cdata = [];
        var existOps = $(obj).combobox('getData');
        for (var i = 0; i < existOps[0].length; i++) {
            cdata.push({ 'id': existOps[0][i].value, 'text': existOps[0][i].text });
        }
    }
    //"<option selected=\"selected\" value=\"" + v + "\">" + text + "</option>";
    var cval = isuserval ? value : document.getElementById(did + "H").value;
    var found = false;
    var opts = "";
    for (var i = 0; i < cdata.length; i++) {
        opts += '<option style="display:none;" value="' + cdata[i].id + '"';
        if (cval == cdata[i].id) {
            opts += ' selected=\"selected\"';
            found = true;
        }
        opts += '>' + cdata[i].text + '</option>';
    }
    $(obj).html(opts);
    $(obj).css("display", "");
    $(obj).css("display", "none");
    $.data(obj, "combobox", null);
    var ocontent = $(obj).next("span");
    if (ocontent) ocontent.remove();
    var sch = $(obj).attr("onChange");
    $(obj).combobox({
        onChange: function(newValue, oldValue) {
            setHideVal(did, newValue); //document.getElementById(did + "H").value = newValue;
            saveEdit = true;
            DataChange();
            $(obj).trigger("change");
        }
    });
    if (found) {
        $(obj).combobox('setValue', cval);
    } else {
        var opts = $.data(obj, "combobox").options;
        var valobj = {};
        valobj[opts.valueField] = cval;
        valobj[opts.textField] = cval;
        $(obj).combobox('setValue', valobj);
    }
    fixElementFontSize($(obj).next("span").find("textarea").eq(0));

    var tidx = $(obj).attr("tabindex");
    if (tidx)
        $(obj).next("span").find(".combobox-text").attr("tabindex", tidx);
    if (isuserval) {
        document.getElementById(did + "H").value = cval;
        saveEdit = true;
        DataChange();
    }
}

//gid 表单数据表ID
//op 是操作 -1返回数据表ID；0取行数据；1取单元格值；2取单元格Id（无权限时取的是td的Id，有权限是取的是其中控件的Id（对于下拉框，取的是原始select的Id，不可见））；3对单元格控件赋值
//rowIdx 行号
//field 列读取数据项（变相列号）
//uservalue 赋值时用户指定的值
function FormGridOperation(gid, op, rowIdx, field, uservalue) {
    var operRes = null;
    var gridObj = $(document.getElementById(gid));
    if (op == -1) {
        if (gridObj.attr("tagName") == "TABLE" || gridObj.get(0).tagName == "TABLE") return gid;
        else return gridObj.parents("table").attr("id");
    }
    var headernum = GetHeadNum(gridObj);
    var rowData = null, trRow = null;
    var trObjs = gridObj.find("tr[isrow='1']");
    for (var i = 0; i < trObjs.length; i++) {
        var trobj = trObjs[i];
        var rowIndex = $(trobj).attr("rowIndex") - headernum;
        if (rowIndex == rowIdx - 1) {
            rowData = GetRowData(trobj);
            trRow = trobj;
            break;
        }
    }
    switch (op) {
        case 0:
            operRes = rowData;
            break;
        case 1:
        case 2:
            if (field && rowData) {
                for (var fkey in rowData) {
                    if (fkey.toLowerCase() != field.toLowerCase()) continue;
                    if (op == 1) operRes = rowData[fkey].value;
                    else if (op == 2) operRes = rowData[fkey].id;
                }
            }
            break;
        case 3:
            var setobjid = FormGridOperation(gid, 2, rowIdx, field);
            SetFormCtrlValue(setobjid, uservalue);
            break;
    }
    return operRes;
}

//tgid 数据列表ID
//idxId 子控件半ID或列查询字段
//rowcaller所在行调用者，实际上是为了定位行号
//rowIdx 行号
function GetTbGridCtrlValue(tgid, idxId, rowcaller, rowIdx) {
    var resval = "";
    var dyObj = $('#' + tgid);
    var headRows = dyObj.find("tr[isHead='1']");
    rowIdx = GetRowIndex(tgid, rowcaller, rowIdx);
    /*
    if (!rowIdx || rowIdx < 0) {
        rowIdx = parseInt(rowcaller, 10);
        if (rowIdx == rowcaller && rowIdx > 0) {
            rowIdx -= 1;
        }else if (rowcaller) {
            var parentobj = $(rowcaller).parents("tr")[0];
            rowIdx = parentobj.rowIndex - headRows.length;
        } else {
            rowIdx = 0;
        }
    }*/
    if (idxId.indexOf('__') < 0) {
        var datas = jQuery.data(dyObj[0], "datas");
        if (rowIdx >= 0 && rowIdx < datas.rows.length) {
            var tdyobj = datas.rows[rowIdx];
            for (var tdkey in tdyobj) {
                if (tdkey.toLowerCase() == idxId.toLowerCase()) {
                    resval = tdyobj[tdkey];
                    break;
                }
            }
        }
    } else {
        var ctrobjId = tgid + "_r" + (rowIdx + 1) + "_c" + idxId.replace('__', '_');
        var ctrobj = $("#" + ctrobjId);
        if (ctrobj.length == 0) return resval;
        var type = ctrobj.attr("type");
        if (ctrobj.attr("tagName") == "A" || ctrobj.get(0).tagName == "A") {
            resval = ctrobj.attr("href");
        } else if (type == "checkbox") {
            resval = "";
            if (ctrobj.attr("checked") == "checked" || ctrobj.attr("checked"))
                resval = ctrobj.attr('on');
        } else if (type == "radio") {
            resval = "";
            var rname = ctrobj.attr("name");
            if (rname && rname.length > 0) {
                var chked = $("input[name=" + rname + "]:checked");
                if (chked.length) resval = chked.attr('on');
            }
        } else if (type == "image") {
            resval = ctrobj.attr("src")
        } else if (ctrobj.attr("tagName") == "SPAN" || ctrobj.get(0).tagName == "SPAN") {
            resval = ctrobj.attr("value")
        } else {
            resval = ctrobj.val();
        }
    }
    return resval;
}

function SetTabsStyle(id) {
    //return;
    var containertyle = jQuery.data($("#" + id)[0], "containertyle");
    var arrcls = containertyle.split("|");
    if (arrcls[0]) $("#" + id).find(".tabs-header").addClass(arrcls[0]);
    if (arrcls[1]) $("#" + id).find(".tabs-header ul").addClass(arrcls[1]);
    if (arrcls[2]) $("#" + id).find(".tabs-panels").addClass(arrcls[2]);
    if (arrcls[3]) $("#" + id).find(".tabs-scroller-left").addClass(arrcls[3]);
    if (arrcls[4]) $("#" + id).find(".tabs-scroller-right").addClass(arrcls[4]);
}

//设置选项卡显示内容
//id tabs的Id
//title 选项卡标题
//content 选项卡内容
//url需要设置的选项卡的url，content为空时再取url
//urltype url类型0或者1，或者为直接显示url(0)，为获取内容url(1)
function SetTabPanelContent(id, title, content, url, urltype) {
    //getTab
    var tab = $('#' + id).tabs('getTab', title);
    if (content) {
        url = "";
        tab.removeAttr("href");
    } else {
        if (!url) {
            if (!tab.attr("src") || tab.attr("loaded")) return;
            tab.trigger("click");
            tab.attr("loaded", 1);
            url = tab.attr("src");
            urltype = tab.attr("urltype");
        }
        if (urltype == 0) {
            content = '<iframe frameborder="0"  src="' + url + '" style="width:100%;height:100%;"></iframe>'; // scrolling="yes"
            url = "";
        }
    }
    setTimeout(function(){
    $('#' + id).tabs('update', { 'tab': tab, 'options': { 'content': content, 'href': url}}); }, 100);   
    //tab.panel("options").content = "123";
}

//SaveType 附件来源（可以为 数据库，FTP服务器，网站目录 之一 ）
//setName 查询附件所在的数据集（如： 『附件动态查询』）
//setkeyword 数据集sql中的占位查询符
//pathField 附件信息字段(当为数据库时，是附件的名称，如‘图画.tiff’；当为FTP服务器时，是ftp服务器名称@附件名称的组合，如‘3315B79E-20E4-45B1-9F00-94C7DCC3F41E@PictureShow.zip’；当为网站目录是，是附件相对路径，如‘uploadDir\files\date.htm’)
//queryItem 附件内容字段（仅当SaveType为数据库时，才传入此变量值，其余情况需传入'')
function DownLoadData(SaveType, setName, setkeyword, pathField, queryItem) {
    setkeyword = setkeyword ? setkeyword : "";
    if (SaveType != "数据库" && SaveType != "FTP服务器" && SaveType != "网站目录") SaveType = "数据库";
    //var aurl = "../appservice/OuputFile.ashx?action=download&aid=e7e06965-95b5-40bf-b0fd-39bf9aa44889&wid=32b4606f-a22b-4d76-a3aa-2f58adfe0907&stepid=ee9ea9d9-6ac8-40cf-af60-b7b391582ed9";
    var aurl = "../appservice/UploadControl.ashx?action=download&fid=" + $("#hfid").val() + "&SaveType=" + commFun.DoubleStr(SaveType) + "&Db_QuerySetId=" + commFun.DoubleStr(setName) + "&Db_QueryItem=" + commFun.DoubleStr(queryItem) + "&pathField=" + commFun.DoubleStr(pathField) + "&input_index=" + $("#hinput_index").val() + "&iidPlus=" + $("#hIidPlus").val() + "&filterKeyStr=" + commFun.DoubleStr(setkeyword);
    var prepDlg = null;
    $.fileDownload(aurl, {
        /*preparingMessageHtml: "We are preparing your report, please wait...",         
		failMessageHtml: "There was a problem generating your report, please try again."*/
        prepareCallback: function(url) {
        prepDlg = $('<div title="提示" modal="true" style="width:400px;height:150px;font-weight:bold;padding:10px;top:110px;">').html("<br />正在准备下载，请稍候...").dialog();
        },
        successCallback: function(url) {
            prepDlg.dialog('close');
            // ie 6 will block alert('You just got a file download dialog or ribbon for this URL :' + url);
        },
        failCallback: function(html, url) {
            prepDlg.dialog('close');
            html = result.replace(/^<pre[^>]*>/i, "").replace(/<\/pre>$/i, "");
            alert('下载失败，发生错误\r\n' + html);
        }
    });
}